package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.conf.ApplicationConf;
import com.authine.cloudpivot.ext.dto.*;
import com.authine.cloudpivot.ext.dto.kanban.KanbanDto;
import com.authine.cloudpivot.ext.dto.kanban.OperationKanbanQueryDto;
import com.authine.cloudpivot.ext.enums.MessageEnum;
import com.authine.cloudpivot.ext.enums.ServiceEnumType;
import com.authine.cloudpivot.ext.utils.BoUtils;
import com.authine.cloudpivot.ext.utils.KanbanJdbcUtil;
import com.authine.cloudpivot.ext.utils.PmUtil;
import com.authine.cloudpivot.ext.utils.system.SessionUser;
import com.authine.hermes.app.launcher.response.SingleResponse;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import java.util.*;

import static com.authine.cloudpivot.ext.conf.ApplicationConf.*;
import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Slf4j
@Path("WorkIndexService")
public class WorkIndexService extends ApplicationService {
    private JdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(JdbcTemplate.class);
    private final TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);
    private final SessionUser sessionUser = new SessionUser();

    @Path("queryIndexKanBan")
    @POST
    @Operation(summary = "首页-数据统计", tags = CUSTOM_SERVICE)
    public SingleResponse<List<QueryIndexKanBanVo>> queryIndexKanBan() {
        String orgName = "";
        if(!sessionUser.isPm()){
            OrgVo orgVo = PmUtil.getOrgOrganization("");
            orgName = orgVo.getName();
        }

        //今日发布询价商品数
        List<QueryIndexKanBanVo> todayInquiryTimes = KanbanJdbcUtil.queryInquiryByTimeToday(orgName);

        //昨日询价商品次数
        List<QueryIndexKanBanVo> yesterdayInquiryTimes = KanbanJdbcUtil.queryQuotationByTimeYesterday(orgName);

        //今日定标次数
        List<QueryIndexKanBanVo> dingbiaoTimes = KanbanJdbcUtil.queryDingbiaoByTimeToday(orgName);

        //昨日报价次数
        List<QueryIndexKanBanVo> quotationTimes = KanbanJdbcUtil.queryQuotationByYesterday(orgName);

        todayInquiryTimes.addAll(yesterdayInquiryTimes);
        todayInquiryTimes.addAll(dingbiaoTimes);
        todayInquiryTimes.addAll(quotationTimes);

        return SingleResponse.of(todayInquiryTimes);
    }


    @Path("queryIndexPageService")
    @POST
    @Operation(summary = "首页-动态更新", tags = CUSTOM_SERVICE)
    public SingleResponse<QueryIndexVo> queryIndexPageService() {
        OrgVo organization = PmUtil.getOrgOrganization("");
        if (StringUtils.isEmpty(organization)) {
            throw new BizException("组织信息为空");
        }
        QueryIndexVo.QueryIndexVoBuilder indexVoBuilder = QueryIndexVo.builder();
        //平台通知 时间倒序 limit 10
        String noticeQuery = "select " +
                "id," +
                "content," +
                "type_name," +
                "number," +
                "createdBy," +
                "modifiedTime," +
                "modifiedBy," +
                "sender_id," +
                "sender," +
                "receiver_id," +
                "receiver," +
                "createdTime," +
                "`read`," +
                "type " +
                "from " + ApplicationConf.MESSAGE + " where deleted = 0 and type = 'NOTICE'  order by createdTime limit 10";
        log.info("平台通知 sql：{}",noticeQuery);
        List<MessageVo> queryForList = jdbcTemplate.query(noticeQuery, (rs, rowNum) ->
                MessageVo.builder()
                        .content(rs.getString("content"))
                        .createdBy(rs.getString("createdBy"))
                        .createdTime(rs.getTimestamp("createdTime"))
                        .id(rs.getString("id"))
                        .modifiedTime(rs.getTimestamp("modifiedTime"))
                        .sender(rs.getString("sender"))
                        .sender_id(JSON.parseObject(rs.getString("sender_id"), SelectorFormat.class))
                        .modifiedTime(rs.getTimestamp("modifiedTime"))
                        .receiver_id(JSON.parseObject(rs.getString("receiver_id"), SelectorFormat.class))
                        .receiver(rs.getString("receiver"))
                        .read(rs.getBoolean("read"))
                        .type(rs.getString("type"))
                        .type_name(rs.getString("type_name"))
                        .build());
        indexVoBuilder.notice(queryForList);
        //平台角色  查询全部询价单  全部报价单  全部付款 的前5  对结果进行消息重构
        if (PmUtil.isPm()) {
            String remindTime = PmUtil.dateFormatStrYYYYMMddhhmmss(new Date(System.currentTimeMillis() + 12 * 60 * 60 * 1000));
            String nowTime = PmUtil.dateFormatStrYYYYMMddhhmmss(new Date());
            //报价消息
            String quotationGoodsQuery = "select " +
                    "id," +
                    "modifiedBy," +
                    "modifiedTime," +
                    "createdBy," +
                    "createdTime," +
                    "vendor_organization_id" +
                    " from " + QUOTATION +
                    " where expire <= '" + remindTime + "' and expire >= '" + nowTime + "' and  deleted = 0 order by createdTime desc limit 5";
            indexVoBuilder.quotation(executeSql(quotationGoodsQuery, "vendor_organization_id", "发布了一个报价，报价单号【"));
            //询价消息
            String inquiryQuery = "select " +
                    "distinct t1.id as id," +
                    "t1.modifiedBy," +
                    "t1.modifiedTime," +
                    "t1.createdBy," +
                    "t1.createdTime," +
                    "t1.organization_id " +
                    " from " + INQUIRY +
                    " t1 join " + INQUIRY_GOODS + " t2 on t1.id = t2.inquiry_id " +
                    "where t1.vendor_scope = 2 and t2.quotation_goods_status in(3,4,5) and t1.deleted = 0 and t2.deleted = 0 order by t1.createdTime desc limit 5";
            indexVoBuilder.inquiry(executeSql(inquiryQuery, "organization_id", "发布了一个询价，询价单号【"));
            //付款消息
            String payQuery = "select " +
                    "id," +
                    "modifiedBy," +
                    "modifiedTime," +
                    "createdBy," +
                    "createdTime," +
                    "organization_name from " + CUSTOMERORDER +
                    " where deleted = 0 and order_customer_status = 'UpcomingConfirm' order by createdTime desc limit 5";
            log.info("付款消息 sql：{}",payQuery);
            List<MessageVo> payVoList = jdbcTemplate.query(payQuery, (rs, rowNum) ->
                    MessageVo.builder()
                            .id(rs.getString("id"))
                            .type(MessageEnum.EVENT.getType())
                            .type_name(MessageEnum.EVENT.getDesc())
                            .content((rs.getString("organization_name"))
                                    .concat("客户订单号:").concat("【").concat(rs.getString("id")).concat("】，付款成功！"))
                            .modifiedTime(rs.getTimestamp("modifiedTime"))
                            .modifyBy(rs.getString("modifiedBy"))
                            .build()
            );
            indexVoBuilder.pay(payVoList);
        } else if (sessionUser.isVendor()) {
            //供应商 查询所有询价  自己的报价   给自己的付款
            //报价消息
            String remindTime = PmUtil.dateFormatStrYYYYMMddhhmmss(new Date(System.currentTimeMillis() + 12 * 60 * 60 * 1000));
            String nowTime = PmUtil.dateFormatStrYYYYMMddhhmmss(new Date());
            String orgId = Objects.requireNonNull(PmUtil.getOrgOrganization("")).getId();
            String quotationGoodsQuery = "select " +
                    "id," +
                    "modifiedBy," +
                    "modifiedTime," +
                    "createdBy," +
                    "createdTime," +
                    "vendor_organization_id" +
                    " from " + QUOTATION_GOODS +
                    " where expire <= '" + remindTime + "' and expire >= '" + nowTime + "' " +
                    "and vendor_organization_id like concat('%','" + orgId + "','%') and  deleted = 0 order by createdTime desc limit 5";
            indexVoBuilder.quotation(executeSql(quotationGoodsQuery, "vendor_organization_id", "发布了一个报价，报价单号【"));
            //询价消息
            String inquiryQuery = "select " +
                    "t1.id," +
                    "t1.modifiedBy," +
                    "t1.modifiedTime," +
                    "t1.createdBy," +
                    "t1.createdTime," +
                    "t1.organization_id " +
                    " from " + INQUIRY + " t1 join " +
                    "" + INQUIRY_GOODS + " t2 on t1.id = t2.inquiry_id join " +
                    "" + QUOTATION_GOODS + " t3 on t3.inquiry_goods_id = t2.id " +
                    "where t1.vendor_scope = 2 and t2.quotation_goods_status in(3,4,5) and t3.vendor_organization_id like concat('%','" + orgId + "','%') " +
                    "and t1.deleted = 0 and t2.deleted = 0 and t3.deleted = 0 group by id order by t1.createdTime desc limit 5";
            indexVoBuilder.inquiry(executeSql(inquiryQuery, "organization_id", "发布了一个询价，询价单号【"));
            //付款消息
            String payQuery = "select " +
                    "t1.id," +
                    "t1.modifiedBy," +
                    "t1.modifiedTime," +
                    "t1.createdBy," +
                    "t1.createdTime," +
                    "t1.organization_name from " + I_ORDERCENTER_CUSTOMERORDER + " t1 join " +
                    "" + ORDER_VENDOR + " t2 on t1.id = t2.order_customer_id" +
                    " where t1.deleted = 0 and t2.deleted = 0 " +
                    " and t1.order_customer_status = 'UpcomingConfirm' " +
                    " and t2.organization_id like concat('%','" + orgId + "','%') group by id order by t1.createdTime desc limit 5";
            log.info("付款消息 sql：{}",payQuery);
            List<MessageVo> payVoList = jdbcTemplate.query(payQuery, (rs, rowNum) ->
                    MessageVo.builder()
                            .id(rs.getString("id"))
                            .type(MessageEnum.EVENT.getType())
                            .type_name(MessageEnum.EVENT.getDesc())
                            .content((rs.getString("organization_name"))
                                    .concat("客户订单号:").concat("【").concat(rs.getString("id")).concat("】，付款成功！"))
                            .modifiedTime(rs.getTimestamp("modifiedTime"))
                            .modifyBy(rs.getString("modifiedBy"))
                            .build()
            );
            indexVoBuilder.pay(payVoList);
        } else if (sessionUser.isCustomer()) {
            //客户 查询自己的询价  供应商给自己的报价   自己的付款
            //报价消息
            String remindTime = PmUtil.dateFormatStrYYYYMMddhhmmss(new Date(System.currentTimeMillis() + 12 * 60 * 60 * 1000));
            String nowTime = PmUtil.dateFormatStrYYYYMMddhhmmss(new Date());
            String orgId = Objects.requireNonNull(PmUtil.getOrgOrganization("")).getId();
            String quotationGoodsQuery = "select " +
                    "t1.id," +
                    "t1.modifiedBy," +
                    "t1.modifiedTime," +
                    "t1.createdBy," +
                    "t1.createdTime," +
                    "t1.vendor_organization_id" +
                    " from " + QUOTATION_GOODS + " t1 join " +
                    "" + INQUIRY_GOODS + " t2 on t1.inquiry_goods_id = t2.id join " +
                    "" + INQUIRY + " t3 on t2.inquiry_id = t3.id" +
                    " where t1.expire <= '" + remindTime + "' and t1.expire >= '" + nowTime + "' " +
                    "and t3.organization_id like concat('%','" + orgId + "','%') and t1.deleted = 0 and t2.deleted = 0 and t3.deleted = 0 " +
                    "order by t1.createdTime desc limit 5";
            indexVoBuilder.quotation(executeSql(quotationGoodsQuery, "vendor_organization_id", "发布了一个报价，报价单号【"));
            //询价消息
            String inquiryQuery = "select " +
                    "t1.id," +
                    "t1.modifiedBy," +
                    "t1.modifiedTime," +
                    "t1.createdBy," +
                    "t1.createdTime," +
                    "t1.organization_id " +
                    " from " + INQUIRY +
                    " t1 join " + INQUIRY_GOODS + " t2 on t1.id = t2.inquiry_id " +
                    "where t1.vendor_scope = 2 and t2.quotation_goods_status in(3,4,5) and t1.organization_id like concat('%','" + orgId + "','%') " +
                    "and t1.deleted = 0 and t2.deleted = 0 group by id order by t1.createdTime desc limit 5";
            indexVoBuilder.inquiry(executeSql(inquiryQuery, "organization_id", "发布了一个询价，询价单号【"));
            //付款消息
            String payQuery = "select " +
                    "id," +
                    "modifiedBy," +
                    "modifiedTime," +
                    "createdBy," +
                    "createdTime," +
                    "organization_name from " + I_ORDERCENTER_CUSTOMERORDER +
                    " where deleted = 0 " +
                    " and order_customer_status = 'UpcomingConfirm' " +
                    " and organization_id like concat('%','" + orgId + "','%') order by createdTime desc limit 5";
            log.info("付款消息 sql：{}",payQuery);
            List<MessageVo> payVoList = jdbcTemplate.query(payQuery, (rs, rowNum) ->
                    MessageVo.builder()
                            .id(rs.getString("id"))
                            .type(MessageEnum.EVENT.getType())
                            .type_name(MessageEnum.EVENT.getDesc())
                            .content((rs.getString("organization_name"))
                                    .concat("客户订单号:").concat("【").concat(rs.getString("id")).concat("】，付款成功！"))
                            .modifiedTime(rs.getTimestamp("modifiedTime"))
                            .modifyBy(rs.getString("modifiedBy"))
                            .build()
            );
            indexVoBuilder.pay(payVoList);
        }
        return SingleResponse.of(indexVoBuilder.build());

    }

    private List<MessageVo> executeSql(String quotationGoodsQuery, String id, String s) {
        log.info("执行sql ：{}",quotationGoodsQuery);
        return jdbcTemplate.query(quotationGoodsQuery, (rs, rowNum) ->
                MessageVo.builder()
                        .id(rs.getString("id"))
                        .type(MessageEnum.EVENT.getType())
                        .type_name(MessageEnum.EVENT.getDesc())
                        .content(StringUtils.isEmpty(rs.getString(id))?"":(JSON.parseObject(rs.getString(id), SelectorFormat.class).getName())
                                .concat(s)
                                .concat(rs.getString("id")).concat("】，请查看！"))
                        .modifiedTime(rs.getTimestamp("modifiedTime"))
                        .modifyBy(rs.getString("modifiedBy"))
                        .build()
        );
    }

}
